package com.dc.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dc.common.constants.ConstantsCommon;
import com.dc.common.em.EnumOperationModule;
import com.dc.common.model.BaseModel;
import com.dc.system.mapper.UserMapper;
import com.dc.system.mapper.SystemMapper;
import com.dc.system.model.SysMenu;
import com.dc.system.model.SysRolePermission;
import com.dc.system.model.SysUser;
import com.dc.system.service.SystemService;

@Service
public class SystemServiceImpl implements SystemService {

	@Autowired
	private UserMapper sysUserMapper;

	@Autowired
	private SystemMapper systemMapper;

	@Override
	public BaseModel getMenu(BaseModel baseModel, HttpServletRequest request) throws Exception {
		// 获取session中当前登陆人
		SysUser sysUser = (SysUser) request.getSession().getAttribute(ConstantsCommon.LOGIN_USERINFO);
		// 获取用户有权限的菜单code值
		List<SysRolePermission> permissions = systemMapper.getUserPermissionCode(sysUser);
		//获取所有菜单
		List<SysMenu> menus = systemMapper.getAllMenus();
		
		for (int i = 0; i < menus.size(); i++) {
			for (int j = 0; j < menus.get(i).getSysMenus().size(); j++) {
				for (int k = 0; k < permissions.size(); k++) {
					if(!permissions.get(i).getCode().equals(menus.get(i).getSysMenus().get(j).getCode())){
						menus.get(i).getSysMenus().remove(j);
					}
				}
			}
		}
		baseModel.setData(menus);
		return baseModel;
	}

	@Override
	public BaseModel getModuleHiddenIds(BaseModel baseModel, HttpServletRequest request,int code)
			throws Exception {
		SysUser sysUser = (SysUser) request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
		Map map = new HashMap<String, Object>();
		map.put("user_id", sysUser.getUser_id());
		map.put("code", code);
		//获取模块所有ids以及用户的权限value
		SysRolePermission sysRolePermission = systemMapper.getModuleHiddenIds(map);
		//得到需要隐藏的按钮ids
		String[] ids = sysRolePermission.getIds().split(",");
		char[] c = sysRolePermission.getPermission_value().toCharArray();
		StringBuffer stringBuffer = new StringBuffer();
		for (int i = 0; i < c.length; i++) {
			if (!"0".equals(c[i] + "")) {
				if (stringBuffer.length() == 0) {
					stringBuffer.append(ids[i]);
				} else {
					stringBuffer.append("," + ids[i]);
				}
			}
		}
		baseModel.setCode(0);
		baseModel.setData(stringBuffer.toString());
		return baseModel;
	}

}
